var express = require('express');
var router = express.Router();
var validate = require('../common/validate.js');
var xss = require('xss');
var mongoose = require('mongoose');
var permission = require('../common/permission.js');
var moment = require('moment');
var async = require('async');

router.get('/', blog);
router.get('/new', permission.checkLogin, create);
router.post('/new', createPost);    //新建文章
router.get('/getList', getList);    //获取分页的文章列表
router.get('/article/:id', getArticle); //文章页
router.get('/thumbup', thumbup);    //点赞功能
router.get('/love', love);  //收藏功能
router.get('/edit', edit);  //修改文章
router.post('/edit', editPost);  //修改文章
router.get('/getArticleInfo', getArticleInfo);  //获取文章信息的异步接口
router.get('/delete', deleteArticle);    //删除文章
router.post('/comment', commentArticle);    //评论文章
router.post('/reply', reply);    //回复接口
router.get('/user/:id', getUserArticle);    //用户文章列表
router.get('/getUserList', getUserList);    //用户文章列表异步接口
router.get('/message', permission.checkLogin, getMessage); //未读消息入口
router.get('/lookComment', lookComment); //查看评论
router.get('/collect', permission.checkLogin, collect); //查看收藏
router.get('/getCollectArticle', getCollectArticle); //查看收藏异步接口

router.get('/getBlogScore', permission.checkLogin, getBlogScore);   //外部接口,供绩效考核页面使用

function getBlogScore(req, res, next) {
    if (!req.session.user) {
        return res.send('同学别闹');
    }

    var User = mongoose.model('User');
    User.find({}, function(err, results) {
        if (err) throw err;
        var maxVisted = 0,
            maxThumbed = 0,
            maxCommented = 0;
        results.forEach(function(result) {
            if (result.visitedNum > maxVisted) {
                maxVisted = result.visitedNum;
            }
            if (result.thumbedNum > maxThumbed) {
                maxThumbed = result.thumbedNum;
            }
            if (result.commentedNum > maxCommented) {
                maxCommented = result.commentedNum;
            }
        });
        var obj = {status: 200};
        obj.data = {
            visitedNum: {
                value: req.session.user.visitedNum,
                max: maxVisted
            },
            thumbedNum: {
                value: req.session.user.thumbedNum,
                max: maxThumbed
            },
            commentedNum: {
                value: req.session.user.commentedNum,
                max: maxCommented
            }
        }
        res.json(obj);
    })
}


function collect(req, res, next) {

    //获取未读信息的条数
    if (req.session.user) {
        var User = mongoose.model('User');
        User.findOne({_id: req.session.user['_id']}, function (err, result) {
            if (err) throw err;

            var newUser = result;
            var count = 0;
            console.log('user呢???')
            console.log(result.commentsBy);
            result.commentsBy.forEach(function (comment) {
                if (comment.isRead == false) {
                    count++;
                }
            });

            //获取收藏条数
            User.findOne({_id: req.session.user['_id']}, function (err, result) {
                if (err) throw err;

                return res.render('blog/collection', {
                    title: 'EUX博客',
                    user: newUser,
                    mesNumNotRead: count,
                    collectNum: result.loveArticles.length
                });
            });
        });


    }

}

function getCollectArticle(req, res, next) {
    if (!req.session.user) {
        return res.send('同学别闹!');
    }

    var page = req.query.page || 1;

    console.log(page);

    var pageCount = 10; //每页10条数据

    var Article = mongoose.model('Article');

    Article.count({}, function(err, length) {
        if (err) throw err;
        var pageAmount = Math.ceil(length / pageCount); //向上取整,分页总数
        var remainPage = pageAmount - page;
        console.log('分页总数'+pageAmount, '剩余分页'+remainPage);

        Article.find({_id: {$in: req.session.user.loveArticles}}).sort({date: -1}).skip((page - 1) * pageCount).limit(pageCount).exec(function (err, results) {
            if (err) throw err;
            var obj = {status: 200};
            //只传出前200个字符
            obj.data = results.map(function(result) {
                result.content = result.content.substr(0, 200);
                return result;
            });
            console.log(obj.data);
            obj.remainPage = remainPage;
            res.json(obj);
        });

    });
}

function lookComment(req, res, next) {

    //将user中的isRead设置为true

    var User = mongoose.model('User');

    //无奈用date来标识。。。。不想写了
    //时间戳竟然被转成了Double类型,我也是醉了。。。。

    User.update({
        _id: req.session.user['_id'],
        'commentsBy.date': Number(req.query.t)
    }, {$set: {'commentsBy.$.isRead': true}}, function (err, result) {
        if (err) throw err;
        console.log('更改成功!!!');
        res.redirect('/blog/article/' + req.query.bid);
    });

}

function getMessage(req, res, next) {
    //获取未读信息的条数

    var User = mongoose.model('User');
    User.findOne({_id: req.session.user['_id']}, function (err, result) {
        if (err) throw err;

        var newUser = result;
        newUser.commentsBy = newUser.commentsBy.reverse();

        var count = 0;
        console.log('user呢???')
        console.log(result.commentsBy);
        result.commentsBy.forEach(function (comment) {
            if (comment.isRead == false) {
                count++;
            }
        });

        //获取收藏条数
        User.findOne({_id: req.session.user['_id']}, function (err, result) {
            if (err) throw err;

            return res.render('blog/message', {
                title: 'EUX博客',
                user: newUser,
                mesNumNotRead: count,
                collectNum: result.loveArticles.length
            });
        });
    });


}

function getUserList(req, res, next) {
    if (!req.query.uid) {
        return res.send('同学别闹!');
    }
    var page = req.query.page || 1;

    console.log(page);

    var pageCount = 10; //每页10条数据

    var Article = mongoose.model('Article');

    Article.count({}, function(err, length) {
        if (err) throw err;
        var pageAmount = Math.ceil(length / pageCount); //向上取整,分页总数
        var remainPage = pageAmount - page;
        console.log('分页总数'+pageAmount, '剩余分页'+remainPage);

        Article.find({uid: req.query.uid}).sort({date: -1}).skip((page - 1) * pageCount).limit(pageCount).exec(function (err, results) {
            if (err) throw err;
            var obj = {status: 200};
            //只传出前200个字符
            obj.data = results.map(function(result) {
                result.content = result.content.substr(0, 200);
                return result;
            });
            console.log(obj.data);
            obj.remainPage = remainPage;
            res.json(obj);
        });

    });
}

function getUserArticle(req, res, next) {
    if (!req.params.id) {
        return res.send('同学别闹!');
    }

    var User = mongoose.model('User');
    User.findById(req.params.id, function (err, result) {
        if (err) throw err;

        res.render('blog/user', {
            title: 'EUX博客',
            user: result
        });
    })

}

function reply(req, res, next) {
    if (!req.body.cid || !req.body.uid || !req.body.bid) {
        return res.send('同学别闹!');
    }

    var obj = validateComment(req.body);
    if (obj.status == 400) {
        return res.json(obj);
    }

    console.log(obj);

    var User = mongoose.model('User');
    //得到回复的是谁的信息
    User.findById(req.body.uid, function (err, result) {
        if (err) throw err;
        console.log(result);

        var data = {
            uid: req.session.user['_id'],
            username: req.session.user.username,
            usericon: req.session.user.usericon,
            userdep: renderDep(req.session.user.department),
            date: Date.now(),
            content: req.body.comment,
            replyUsername: result.username, //回复的是谁
            replyUserdep: renderDep(result.department), //回复的是谁
            isRead: false,   //标记为未读
            bid: req.body.bid
        }

        //更新Comment表的replyList
        var Comment = mongoose.model('Comment');

        Comment.update({_id: req.body.cid}, {$push: {replyList: data}}, function (err, result) {
            if (err) throw err;
            console.log(result);

            //更新user表

            User.update({_id: req.body.uid}, {$push: {commentsBy: data}}, function (err, result) {
                if (err) throw err;

                console.log(result);
                //评论成功
                return res.json(obj);
            });
        });


    });


}

function commentArticle(req, res, next) {
    if (!req.body.bid || !req.body.uid) {
        return res.send('同学别闹!');
    }

    var obj = validateComment(req.body);
    if (obj.status == 400) {
        return res.json(obj);
    }

    var data = {};
    if (req.session.user) {
        //如果登录
        data = {
            uid: req.session.user['_id'],
            username: req.session.user.username,
            usericon: req.session.user.usericon,
            userdep: renderDep(req.session.user.department),
            date: Date.now(),
            content: req.body.comment,
            isRead: false,   //标记为未读
            bid: req.body.bid
        }
    } else {
        //未登录需要记录ip
        data = {
            username: req.body.username,
            useremail: req.body.useremail,
            userip: getClientIp(req),
            usericon: 'default_boy.png',
            content: req.body.comment,
            date: Date.now(),
            userdep: '游客',
            isRead: false,   //标记为未读
            bid: req.body.bid
        }
    }

    //存入Comment表
    var Comment = mongoose.model('Comment');
    var comment = new Comment(data);

    comment.save(function (err, result) {
        if (err) throw err;

        console.log(result);
        var cid = result['_id'];

        //将cid存入Article表
        var Article = mongoose.model('Article');
        Article.update({_id: req.body.bid}, {$push: {comments: cid}}, function (err, result) {
            if (err) throw err;

            console.log(result);
            //因为User表中并不需要replyList,所以直接存储data更加方便一些
            var User = mongoose.model('User');
            User.update({_id: req.body.uid}, {$push: {commentsBy: data}}, function (err, result) {
                if (err) throw err;

                //user的被评论数数加一
                User.update({_id: req.body.uid}, {$inc: {commentedNum: 1}}, function (err, result) {
                    if (err) throw err;
                    console.log('评论量加一');
                });

                console.log(result);
                //评论成功
                return res.json(obj);
            });
        });

    });

}

function getClientIp(req) {
    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
};

function validateComment(data) {

    var obj = {
        status: 400,
        msg: '评论成功!'
    };

    if (data.username && validate.emptystring(data.username)) {
        obj.msg = '输入不能为空!';
        return obj;
    }
    if (data.useremail && validate.emptystring(data.useremail)) {
        obj.msg = '输入不能为空!';
        return obj;
    }

    if (data.username && data.username.length > 8) {
        obj.msg = '输入超限!';
        return obj;
    }

    if (data.comment.length > 256) {
        obj.msg = '输入超限!';
        return obj;
    }

    if (data.useremail && !validate.isEmail(data.useremail)) {
        obj.msg = '格式不符!';
        return obj;
    }

    if (data.username && !validate.normalstring(data.username)) {
        obj.msg = '非法字符!';
        return obj;
    }

    // if (!validate.normalstring(data.comment)) {
    //     obj.msg = '非法字符!';
    //     return obj;
    // }

    obj.status = 200;

    return obj;
}

function deleteArticle(req, res, next) {
    if (!req.query.bid || !req.session.user) {
        return res.send('同学别闹!');
    }

    var Article = mongoose.model('Article');
    Article.findById(req.query.bid, function (err, result) {
        if (err) throw err;
        var article = result;

        var User = mongoose.model('User');
        User.findById(result.uid, function (err, result) {
            if (err) throw err;

            //如果试图删除别人的文章
            if (req.session.user['_id'] != result['_id']) {
                return res.send('同学别闹!');
            }

            Article.remove({_id: req.query.bid}, function (err) {
                if (err) throw err;
                res.send('删除成功!');
            })
        });

    });
}


function editPost(req, res, next) {
    if (!req.session.user) {
        return res.send('同学别闹!');
    }

    var obj = validateData(req.body);
    console.log(obj);
    if (obj.status == 400) {
        return res.send(JSON.stringify(obj));
    }

    req.body.tags = req.body.tags.map(function (tag) {
        return xss(tag);
    });

    var data = {
        title: xss(req.body.title),
        classify: parseInt(req.body.classify),
        tags: req.body.tags,
        content: xss(req.body.content, {
            onTagAttr: function (tag, name, value, isWhiteAttr) {
                if (tag == 'img' && name == 'src') {
                    return 'src="' + xss.friendlyAttrValue(value) + '"';
                }
            }
        })
    }


    var Article = mongoose.model('Article');
    Article.update({_id: req.body.bid}, data, function (err, result) {
        if (err) throw err;
        console.log(result);
        return res.send(JSON.stringify(obj));
    });

}

function getArticleInfo(req, res, next) {
    if (!req.query.bid) {
        return res.send('同学别闹!');
    }

    var Article = mongoose.model('Article');
    Article.findById(req.query.bid, function (err, result) {
        if (err) throw err;

        return res.json(result);
    });
}

function edit(req, res, next) {
    if (!req.query.bid || !req.session.user) {
        return res.send('同学别闹!');
    }

    var Article = mongoose.model('Article');
    Article.findById(req.query.bid, function (err, result) {
        if (err) throw err;
        var article = result;

        var User = mongoose.model('User');
        User.findById(result.uid, function (err, result) {
            if (err) throw err;

            //如果试图编辑别人的文章
            if (req.session.user['_id'] != result['_id']) {
                return res.send('同学别闹!');
            }

            res.render('blog/edit', {
                title: 'EUX博客',
                user: req.session.user,
                article: article
            });
        });

    });
}

function love(req, res, next) {
    var Article = mongoose.model('Article');

    if (!req.session.user) {
        return res.send('同学别闹!');
    }

    var User = mongoose.model('User');
    User.findById(req.session.user['_id'], function (err, result) {
        if (err) throw err;

        if (result.loveArticles.indexOf(req.query.bid) != -1 || !req.query.bid) {
            return res.send('同学别闹!');
        }

        Article.update({_id: req.query.bid}, {$inc: {collected: 1}}, function (err, result) {
            if (err) throw err;
            console.log(result);

            User.update({_id: req.session.user['_id']}, {$push: {loveArticles: req.query.bid}}, function (err, result) {
                if (err) throw err;
                console.log(result);
                res.send('收藏成功!');
            });
        });
    });
}

function thumbup(req, res, next) {
    var Article = mongoose.model('Article');

    if (!req.session.user) {
        return res.send('同学别闹!');
    }

    var User = mongoose.model('User');
    User.findById(req.session.user['_id'], function (err, result) {
        if (err) throw err;

        if (result.thumbArticles.indexOf(req.query.bid) != -1 || !req.query.bid) {
            return res.send('同学别闹!');
        }

        Article.update({_id: req.query.bid}, {$inc: {loved: 1}}, function (err, result) {
            if (err) throw err;
            console.log(result);

            User.update({_id: req.session.user['_id']}, {$push: {thumbArticles: req.query.bid}}, function (err, result) {
                if (err) throw err;
                console.log(result);

                //user的点赞数数加一
                User.update({_id: req.session.user['_id']}, {$inc: {thumbedNum: 1}}, function (err, result) {
                    if (err) throw err;
                    console.log(result);
                    res.send('点赞成功!');
                });

            });
        });
    });
}

function getArticle(req, res, next) {
    var Article = mongoose.model('Article');

    var User = mongoose.model('User');

    //更新visited字段
    Article.update({_id: req.params.id}, {$inc: {visited: 1}}, function (err, result) {
        if (err) throw err;
        console.log(result);
    });


    Article.findById(req.params.id, function (err, result) {
        if (err) throw err;

        if (!result) {
            return res.send('同学别闹!');
        }

        //user的浏览数数加一
        User.update({_id: result.uid}, {$inc: {visitedNum: 1}}, function (err, result) {
            if (err) throw err;
            console.log('浏览量加一');
        });

        var data = reformatData(result);
        var Comment = mongoose.model('Comment');
        var comments = [];

        //将comments展开
        //每个操作都是异步的,不得不使用一下异步流程库。。。
        async.eachSeries(data.comments, function (item, callback) {

            Comment.findById(item, function (err, result) {
                comments.push(result);
                callback(err, result);
            });

        }, function (err, result) {
            if (err) throw err;

            //修改评论列表
            data.comments = comments;

            //返回这篇文章是否已经点过赞
            if (req.session.user) {
                User.findById(req.session.user['_id'], function (err, result) {
                    if (err) throw err;

                    var thumbed = '';
                    if (result.thumbArticles.indexOf(req.params.id) != -1) {
                        thumbed = 'active';
                    }

                    //是否收藏
                    var collected = '';
                    if (result.loveArticles.indexOf(req.params.id) != -1) {
                        collected = 'active';
                    }

                    console.log(thumbed);

                    //获取未读信息的条数

                    var User = mongoose.model('User');
                    User.findOne({_id: req.session.user['_id']}, function (err, result) {
                        if (err) throw err;

                        var count = 0;
                        console.log('user呢???')
                        console.log(result.commentsBy);
                        result.commentsBy.forEach(function (comment) {
                            if (comment.isRead == false) {
                                count++;
                            }
                        });

                        //获取收藏条数
                        User.findOne({_id: req.session.user['_id']}, function (err, result) {
                            if (err) throw err;

                            return res.render('blog/article', {
                                title: 'EUX博客',
                                user: req.session.user,
                                article: data,
                                thumbed: thumbed,
                                collected: collected,
                                mesNumNotRead: count,
                                collectNum: result.loveArticles.length
                            });
                        });
                    });


                });
            } else {
                res.render('blog/article', {
                    title: 'EUX博客',
                    user: req.session.user,
                    article: data
                });
            }


        });

    });


}

function reformatData(result) {
    var data = {};
    for (var key in result) {
        data[key] = result[key];
    }
    // console.log(data.date);
    data.date = dateFormat(data.date);
    data.classify = renderClassify(data.classify);

    return data;
}

function dateFormat(date) {
    return moment(date).format('YYYY/MM/DD');
}

function renderClassify(classify) {
    switch (classify) {
        case 0:
            return '前端开发';
        case 1:
            return '视觉设计';
        case 2:
            return '交互设计';
        case 3:
            return '后端开发';
        case 4:
            return 'APP开发';
        case 8:
            return '其它';
        default:
            return '未知类别';
    }
}

function getList(req, res, next) {

    var page = req.query.page || 1;

    console.log(page);

    var pageCount = 10; //每页10条数据

    var Article = mongoose.model('Article');

    Article.count({}, function(err, length) {
        if (err) throw err;
        var pageAmount = Math.ceil(length / pageCount); //向上取整,分页总数
        var remainPage = pageAmount - page;
        console.log('分页总数'+pageAmount, '剩余分页'+remainPage);

        Article.find().sort({date: -1}).skip((page - 1) * pageCount).limit(pageCount).exec(function (err, results) {
            if (err) throw err;
            var obj = {status: 200};
            //只传出前200个字符
            obj.data = results.map(function(result) {
                result.content = result.content.substr(0, 200);
                return result;
            });
            console.log(obj.data);
            obj.remainPage = remainPage;
            res.json(obj);
        });

    });


}

function blog(req, res, next) {

    //获取未读信息的条数
    if (req.session.user) {
        var User = mongoose.model('User');
        User.findOne({_id: req.session.user['_id']}, function (err, result) {
            if (err) throw err;

            var count = 0;
            console.log('user呢???')
            console.log(result.commentsBy);
            result.commentsBy.forEach(function (comment) {
                if (comment.isRead == false) {
                    count++;
                }
            });

            //获取收藏条数
            User.findOne({_id: req.session.user['_id']}, function (err, result) {
                if (err) throw err;

                return res.render('blog/index', {
                    title: 'EUX博客',
                    user: req.session.user,
                    mesNumNotRead: count,
                    collectNum: result.loveArticles.length
                });
            });
        });


    } else {
        res.render('blog/index', {
            title: 'EUX博客',
            user: req.session.user
        });
    }

}

function create(req, res, next) {
    res.render('blog/new', {
        title: 'EUX博客',
        user: req.session.user
    })
}

function createPost(req, res, next) {
    if (!req.session.user) {
        return res.send('同学别闹!');
    }

    var obj = validateData(req.body);
    console.log(obj);
    if (obj.status == 400) {
        return res.send(JSON.stringify(obj));
    }

    req.body.tags = req.body.tags.map(function (tag) {
        return xss(tag);
    });

    var data = {
        title: xss(req.body.title),
        classify: parseInt(req.body.classify),
        tags: req.body.tags,
        content: xss(req.body.content, {
            onTagAttr: function (tag, name, value, isWhiteAttr) {
                if (tag == 'img' && name == 'src') {
                    return 'src="' + xss.friendlyAttrValue(value) + '"';
                }
            }
        }),
        uid: req.session.user._id,
        usericon: req.session.user.usericon,
        username: req.session.user.username,
        userdep: renderDep(req.session.user.department)
    }


    var Article = mongoose.model('Article');
    var article = new Article(data);

    article.save(function (err, results) {
        if (err) throw err;
        console.log('博客')
        console.log(results);

        //user的博客数加一
        var User = mongoose.model('User');
        User.update({_id: req.session.user['_id']}, {$inc: {articleNum: 1}}, function (err, result) {
            if (err) throw err;
            obj.bid = results['_id'];
            res.send(JSON.stringify(obj));
        });


    });
}

function renderDep(department) {
    switch (department) {
        case 0 :
            return 'EUX';
        case 1 :
            return '前端美工组';
        case 2 :
            return '后台Web组';
        case 3 :
            return '后台App组';
        case 4 :
            return '影视部';
        case 5 :
            return '市场部';
        case 6 :
            return '新闻部';
        case 7 :
            return '新媒体部';
        case 8 :
            return '产品部';
        case 9 :
            return '公关部';
        default:
            return '未知部门';
    }
}

function validateData(data) {
    var obj = {
        status: 400,
        msg: '发表成功!'
    }
    if (validate.emptystring(data.title)) {
        obj.msg = '输入为空！';
        return obj;
    }
    if (data.title.length > 24) {
        obj.msg = '字数超限！';
        return obj;
    }
    if (isNaN(parseInt(data.classify))) {
        obj.msg = '同学别闹！';
        return obj;
    }
    if(!data.tags) {
        obj.msg = '请至少添加一个标签！';
        return obj;
    }

    data.tags.forEach(function (str) {
        if (str.length > 8) {
            obj.msg = '字数超限！';
            return obj;
        }
        if (!validate.normalstring(str)) {
            obj.msg = '输入中包含非法字符！';
            return obj;
        }
    });

    if (!validate.normalstring(data.title)) {
        obj.msg = '输入中包含非法字符！';
        return obj;
    }

    obj.status = 200;

    return obj;
}

module.exports = router;
